﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MyERP.Models;

namespace MyERP.WebApi
{
    [Route("api/[controller]/[Action]")]
    [ApiController]
    [Authorize(Roles = "admin,q1,q2,q3,q4")]
    public class GoodsController : ControllerBase
    {
        private MyDbContext db;
        public GoodsController(MyDbContext myDbContext)
        {
            db = myDbContext;
        }
        [HttpGet]
        public List<string> AllName()
        {
            return db.Goods.Select(s => s.Name).ToList();
        }
        /// <summary>
        /// 添加物品
        /// </summary>
        /// <param name="sData"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> Add([FromBody] Goods gData)
        {
            //判断供应商是否存在，如果不存在再继续添加供应商
            Goods? s = db.Goods.FirstOrDefault(a => a.Name == gData.Name);
            if (s == null)
            {
                db.Goods.Add(gData);
                await db.SaveChangesAsync();
                return Ok();
            }
            return NotFound();
        }
        /// <summary>
        /// 获取当前库存物品
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public Dictionary<string, int> GetInventory()
        {
            //获取采购物品数量
            var totalPurchased = db.PurchaseOrder
                .GroupBy(po => po.GoodsName)
                .Select(g => new
                {
                    GoodsName = g.Key,
                    TotalPurchased = g.Sum(po => po.Amount)
                })
                .ToDictionary(x => x.GoodsName, x => x.TotalPurchased);

            //获取销售物品数量
            var totalSold = db.SalesTicket
                .GroupBy(po => po.GoodsName)
                .Select(g => new
                {
                    GoodsName = g.Key,
                    TotalPurchased = g.Sum(po => po.Number)
                })
                .ToDictionary(x => x.GoodsName, x => x.TotalPurchased);

            //计算物品库存数量
            //var inventory = totalPurchased
            //    .ToDictionary(x => x.Key,x => x.Value - (totalSold.ContainsKey(x.Key) ? totalSold[x.Key] : 0));
            var allItems = totalPurchased.Keys.Union(totalSold.Keys);

            var inventory = allItems.ToDictionary(
                key =>
                {
                    totalPurchased.TryGetValue(key, out int purchased);
                    totalSold.TryGetValue(key, out int sold);
                    return key;
                },
                key =>
                {
                    totalPurchased.TryGetValue(key, out int purchased);
                    totalSold.TryGetValue(key, out int sold);
                    return purchased - sold; // 允许库存为负数
                }
            );

            return inventory;
        }

        /// <summary>
        /// 获取最近六个月的销售情况
        /// </summary>
        /// <returns></returns>
        /// 
        [HttpGet]
        public ActionResult<List<MonthlySalesSummary>> GetLastSixMonthsSalesSummary()
        {
            var now = DateTime.Now;
            var sixMonthsAgo = now.AddMonths(-6);

            var result = db.SalesTicket
                .Where(so => so.CreateDateTime >= sixMonthsAgo && so.CreateDateTime <= now)
                .GroupBy(so => new { so.CreateDateTime.Year, so.CreateDateTime.Month })
                .Select(g => new MonthlySalesSummary
                {
                    Year = g.Key.Year,
                    Month = g.Key.Month,
                    TotalAmount = g.Sum(so => so.Money)
                })
                .OrderBy(s => s.Year)
                .ThenBy(s => s.Month)
                .ToList();

            return result;
        }

        /// <summary>
        /// 查询本月采购单金额、单据数量
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult<TodayOrderSummaryResponse> QueryMonth()
        {
            var now = DateTime.Now;
            //获取当前月份的第一天
            var firstDayOfMonth = new DateTime(now.Year, now.Month, 1);
            //下个月的第一天
            var firstDayOfNextMonth = firstDayOfMonth.AddMonths(1);

            var result = db.PurchaseOrder
                .Where(p => p.CreateDateTime >= firstDayOfMonth && p.CreateDateTime < firstDayOfNextMonth)
                .GroupBy(p => 1)
                .Select(g => new TodayOrderSummaryResponse
                {
                    OrderCount = g.Count(),
                    TotalAmount = g.Sum(p => p.Money)
                }).FirstOrDefault();

            return result ?? new TodayOrderSummaryResponse { TotalAmount = 0, OrderCount = 0 };
        }

        /// <summary>
        /// 查询今天的采购单金额、单据数量
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult<TodayOrderSummaryResponse> QueryToday()
        {
            var today = DateTime.Today;

            var result = db.PurchaseOrder
                .Where(po => po.CreateDateTime >= today && po.CreateDateTime < today.AddDays(1))
                .GroupBy(po => 1)
                .Select(g => new TodayOrderSummaryResponse
                {
                    OrderCount = g.Count(),
                    TotalAmount = g.Sum(po => po.Money)
                }).FirstOrDefault();
            return result ?? new TodayOrderSummaryResponse { OrderCount = 0, TotalAmount = 0 };
        }
        /// <summary>
        /// 查询今天的销售单金额、单据数量
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult<TodayOrderSummaryResponse> QueryToday2()
        {
            var today = DateTime.Today;

            var result = db.SalesTicket
                .Where(po => po.CreateDateTime >= today && po.CreateDateTime < today.AddDays(1))
                .GroupBy(po => 1)
                .Select(g => new TodayOrderSummaryResponse
                {
                    OrderCount = g.Count(),
                    TotalAmount = g.Sum(po => po.Money)
                }).FirstOrDefault();
            return result ?? new TodayOrderSummaryResponse { OrderCount = 0, TotalAmount = 0 };
        }
        /// <summary>
        /// 查询本月销售单金额、单据数量
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult<TodayOrderSummaryResponse> QueryMonth2()
        {
            var now = DateTime.Now;
            //获取当前月份的第一天
            var firstDayOfMonth = new DateTime(now.Year, now.Month, 1);
            //下个月的第一天
            var firstDayOfNextMonth = firstDayOfMonth.AddMonths(1);

            var result = db.SalesTicket
                .Where(p => p.CreateDateTime >= firstDayOfMonth && p.CreateDateTime < firstDayOfNextMonth)
                .GroupBy(p => 1)
                .Select(g => new TodayOrderSummaryResponse
                {
                    OrderCount = g.Count(),
                    TotalAmount = g.Sum(p => p.Money)
                }).FirstOrDefault();

            return result ?? new TodayOrderSummaryResponse { TotalAmount = 0, OrderCount = 0 };
        }

    }
}
